package com.aiatomic.couting;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.aiatomic.couting.util.HttpUtils;
import com.aiatomic.couting.util.SystemUtil;
import com.aiatomic.couting.util.ValidatorUtils;
import com.aiatomic.couting.widgets.LineEditText;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class BindPhoneActivity extends Activity {
	private Button submit;
	private LineEditText phone;
	private EventHandler eh;
	private Handler handler = new Handler();
	private String msg = "发生未知错误";
	private String openId;
	private String token;
	private String nick;
	private String uName;
	private String uIcon;
	private int channel;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bind_phone);
		TextView txtBack = (TextView) this.findViewById(R.id.txtBack);
		txtBack.setText(R.string.back);
		txtBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		TextView txtNext = (TextView) this.findViewById(R.id.txtNext);
		txtNext.setVisibility(View.INVISIBLE);
		initSMS();
		TextView txtMiddle = (TextView) this.findViewById(R.id.txtMiddle);
		txtMiddle.setText(R.string.name_verify_title);
		openId = getIntent().getStringExtra("openId");
		token = getIntent().getStringExtra("token");
		nick = getIntent().getStringExtra("nick");
		uName = getIntent().getStringExtra("uName");
		uIcon = getIntent().getStringExtra("uIcon");
		channel = getIntent().getIntExtra("channel", 0);
		phone = (LineEditText) this.findViewById(R.id.reg_phone);
		submit = (Button) this.findViewById(R.id.btn_next);
		initEvent();
	}

	private void initEvent() {
	
		final Button btn_sm = (Button) this.findViewById(R.id.get_sms);
		btn_sm.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (!ValidatorUtils.isMobileNO(phone.getText().toString())) {
					phone.setError(getResources().getString(R.string.err_input_phone));
					phone.setFocusable(true);
					return;
				}
				btn_sm.setEnabled(false);
				CountDownTimer timer = new CountDownTimer(CoutingApplication.SMS_TIME, 1000) {
					@Override
					public void onTick(long millisUntilFinished) {
						String txtRepeat = String.format(getResources().getString(R.string.repeat_sms_code),
								millisUntilFinished / 1000);
						btn_sm.setText(txtRepeat);
					}

					@Override
					public void onFinish() {
						btn_sm.setText(R.string.get_sms_code);
						btn_sm.setEnabled(true);
					}
				};
				timer.start();
				SMSSDK.getVerificationCode("86", phone.getText().toString());
			}
		});
		submit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (!ValidatorUtils.isMobileNO(phone.getText().toString())) {
					phone.setError(getResources().getString(R.string.err_input_phone));
					phone.setFocusable(true);
					return;
				}
				TextView txtSmsCode = (TextView) BindPhoneActivity.this.findViewById(R.id.sms_code);
				if (txtSmsCode.getText().toString().isEmpty()) {
					txtSmsCode.setError(getResources().getString(R.string.err_input_sms_code));
					txtSmsCode.setFocusable(true);
					return;
				}
				SMSSDK.submitVerificationCode("86", phone.getText().toString(), txtSmsCode.getText().toString().trim());
				submit.setEnabled(false);
			}
		});
		
	}
	
	private void s_reg(final String openId, final String token, final String nick, final String uName,
			final String uIcon, final int channel, String mobile) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("imei", SystemUtil.getIMEI(BindPhoneActivity.this));
		params.put("device",
				SystemUtil.getDeviceBrand() + ";" + SystemUtil.getSystemModel() + ";" + SystemUtil.getSystemVersion());
		params.put("mobile", mobile);
		params.put("openId", openId);
		params.put("token", token);
		params.put("nick", nick);
		params.put("uName", uName);
		params.put("uIcon", uIcon);
		params.put("platform", String.valueOf(IConstant.PLATFORM));
		params.put("channel", String.valueOf(channel));
		params.put("sign",
				HttpUtils.md5(params.get("imei") + params.get("device") + params.get("openId") + params.get("token")
						+ params.get("nick") + params.get("uName") + params.get("uIcon") + params.get("platform")
						+ params.get("channel") + IConstant.NORMAL_MD5_KEY));
		HttpUtils.post(new Handler() {

			@Override
			public void handleMessage(Message msg) {
				if (msg.what == HttpUtils.CODE_SUCCESS_RQ_100) {
					try {
						JSONObject json = new JSONObject(msg.obj.toString());
						Toast toast = Toast.makeText(BindPhoneActivity.this, json.getString("msg"), Toast.LENGTH_LONG);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
						if (json.getInt("code") == HttpUtils.RET_SUCCESS) {
							Intent intent = new Intent();
							intent.putExtra("openId", openId);
							intent.putExtra("token", token);
							intent.putExtra("nick", nick);
							intent.putExtra("uName", uName);
							intent.putExtra("uIcon", uIcon);
							intent.putExtra("channel", channel);
							setResult(HttpUtils.RET_SUCCESS, intent);
							BindPhoneActivity.this.finish();

						} else {
							BindPhoneActivity.this.submit.setEnabled(true);
						}
					} catch (JSONException e) {
						e.printStackTrace();
						Log.e("", msg.obj.toString());
						Toast toast = Toast.makeText(BindPhoneActivity.this,
								BindPhoneActivity.this.getResources().getString(R.string.server_format_error),
								Toast.LENGTH_LONG);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
						BindPhoneActivity.this.submit.setEnabled(true);
					}
				} else if (msg.what == HttpUtils.CODE_ERROR_RQ_999) {
					BindPhoneActivity.this.submit.setEnabled(true);
					Toast toast = Toast.makeText(BindPhoneActivity.this, ICodeMsg.ERROR_CODES_HTTP.get(msg.what),
							Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
				}
			}

		}, IConstant.CENTER + "/v/Account_c/account_q_create/", params);
	}

	private void initSMS() {

		SMSSDK.setAskPermisionOnReadContact(true);
		// 3.0版本之后的初始化看这里（包括3.0）
		eh = new EventHandler() {

			@Override
			public void afterEvent(int event, int result, Object data) {
				handler.post(new Runnable() {
					@Override
					public void run() {
						submit.setEnabled(true);
					}
				});
				if (result == SMSSDK.RESULT_COMPLETE) {
					// 回调完成
					if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
						handler.post(new Runnable() {
							@Override
							public void run() {
								s_reg(openId, token, nick, uName, uIcon, channel, phone.getText().toString());
							}
						});
						// 提交验证码成功
					} else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
						System.out.println(data);
						// 获取验证码成功
					} else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
						// 返回支持发送验证码的国家列表
					}
				} else {

					Throwable e = (Throwable) data;
					e.printStackTrace();
					try {
						JSONObject err = new JSONObject(e.getMessage());
						int status = err.getInt("status");
						if (ICodeMsg.ERROR_CODES_SMS.containsKey(status)) {
							msg = ICodeMsg.ERROR_CODES_SMS.get(status);
						}
					} catch (JSONException e1) {
						e1.printStackTrace();
					}
					handler.post(new Runnable() {
						@Override
						public void run() {
							submit.setEnabled(true);
							Toast toast = Toast.makeText(BindPhoneActivity.this, msg, Toast.LENGTH_LONG);
							toast.setGravity(Gravity.CENTER, 0, 0);
							toast.show();

						}
					});

				}
			}
		};
		SMSSDK.registerEventHandler(eh); // 注册短信回调
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (eh != null) {
			SMSSDK.unregisterEventHandler(eh);
		}
	}
}
